package com.cff.springbootwork.oauth.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		if (isAjaxRequest(request)) {
			ResultModel rm = new ResultModel(ResultCode.CODE_00014.getCode(), exception.getMessage());
			ObjectMapper mapper = new ObjectMapper();
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			mapper.writeValue(response.getWriter(), rm);
		} else {
			setDefaultFailureUrl("/login.html");
			super.onAuthenticationFailure(request, response, exception);
		}
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
	}
}